import { defineStore } from "pinia"
import { ref, type Ref } from "vue"

export interface Hanfu {
	id: number,
	name: string,
	price: number,
	type: string
}

interface CartHanfu {
	id: number,
	name: string,
	price: number,
	type: string,
	count: number
}

export const useCartStore = defineStore('cart', () => {
	let curCartHanfuClass: Ref<CartHanfu[]> = ref([])
	
	const addHanfu = (hanfu: Hanfu) => {
		
		for (let i = 0; i < curCartHanfuClass.value.length; i++) {
			if (curCartHanfuClass.value[i].type === hanfu.type) {
				curCartHanfuClass.value[i].count++
				return;
			} 

		}
		
		curCartHanfuClass.value.push({
			id: hanfu.id,
			name: hanfu.name,
			price: hanfu.price,
			type: hanfu.type,
			count: 1
		})
		
	}
	
	const delHanfu = (hanfu:Hanfu) => {
		for (let i = 0; i < curCartHanfuClass.value.length; i++) {
			if (curCartHanfuClass.value[i].type === hanfu.type) {
				
				if (curCartHanfuClass.value[i].count === 1) {
					curCartHanfuClass.value.splice(i,1)
					return;
				}
				
				curCartHanfuClass.value[i].count--
				return;
			} 
		
		}
	}
	
	const delAllHanfu = () => {
		curCartHanfuClass.value = []
	}
	
	const getCurCartNumber = () => {
		let CartNum = 0
		
		for (let i = 0; i < curCartHanfuClass.value.length; i++) {
			CartNum += curCartHanfuClass.value[i].count
		}
		
		return CartNum
	}
	
	const getPrice = () => {
		let price = 0;
		for (let i = 0; i < curCartHanfuClass.value.length; i++) {
			price += curCartHanfuClass.value[i].price * curCartHanfuClass.value[i].count
		}
		return price
	}
	
	const getCartContent = () => {
		return curCartHanfuClass.value
	}
	
	const getHanfuTypeNum = (type:string) => {
		
		for (let i = 0; i < curCartHanfuClass.value.length; i++) {
			if (curCartHanfuClass.value[i].type === type) {
				return curCartHanfuClass.value[i].count + 0
			}
		}
		
	}
	
	
	return { getPrice, delAllHanfu, getHanfuTypeNum, getCartContent,getCurCartNumber, addHanfu, delHanfu}
}) 